package com.jn.algorithm.day020.question61;

import java.util.List;

/**
 * @author 江南大学1033190417
 * @date 2022/5/11 15:48
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head==null||k==0){
            return head;
        }
        ListNode h = head,end;
        int count = 1;
        while (h.next != null) {//统计个数
            count++;
            h = h.next;
        }
        if(count==1){
            return head;
        }
        end=h;//全部段最后一个
        h=head;
        //分两段
        ListNode e=null;//前一段最后一个
        int c = 0;
        k%=count;
        if(k==0){
            return head;
        }
        while (c < count - k) {
            c++;
            if (c==count-k){
                e=h;
            }
            h=h.next;
        }
        //h变为新的头
        e.next=null;
        end.next=head;
        return h;
    }
    public void print(ListNode node) {
        while (node != null) {
            System.out.print(node.val + "\t");
            node = node.next;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        solution.print(solution.rotateRight(head, 5));
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
